package com.quanshu.shop.goods.view;

import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.BaseFragment;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.exchange.ui.gui.profile.DialogShare;
import com.quanshu.shop.base.data.BroadcastReciverAction;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.brocastreciver.CartUpdateBrocarstReciver;
import com.quanshu.shop.goods.adapter.GoodsInfoDetailAdapter;
import com.quanshu.shop.goods.adapter.GoodsInfoViewPagerAdapter;
import com.quanshu.shop.goods.custom.CartDialogWindow;
import com.quanshu.shop.goods.entity.AddGoodsLikeEntity;
import com.quanshu.shop.goods.entity.GoodsInfoEntity;
import com.quanshu.shop.goods.entity.MyCartEntity;
import com.quanshu.shop.goods.inf.CartUpdateListener;
import com.quanshu.shop.main.api.ShopMainIF;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class GoodsInfoActivity extends BaseActivity implements CartUpdateListener {

    @BindView(R.id.goods_info_img_rl)
    RelativeLayout goodsInfoImgRl;
    @BindView(R.id.goods_info_ns)
    NestedScrollView goodsInfoNs;
    @BindView(R.id.goods_info_back)
    FrameLayout goodsInfoBack;
    @BindView(R.id.goods_info_share)
    FrameLayout goodsInfoShare;
    @BindView(R.id.goods_info_title)
    RelativeLayout goodsInfoTitle;
    @BindView(R.id.goods_info_dw)
    TextView goodsInfoDw;
    @BindView(R.id.goods_info_money)
    TextView goodsInfoMoney;
    @BindView(R.id.goods_info_gp)
    TextView goodsInfoGp;
    @BindView(R.id.goods_info_njf)
    TextView goodsInfoNjf;
    @BindView(R.id.goods_info_title_txt)
    TextView goodsInfoTitleTxt;
    @BindView(R.id.goods_info_line)
    ConstraintLayout goodsInfoLine;
    @BindView(R.id.goods_info_rl)
    RecyclerView goodsInfoRl;
    @BindView(R.id.goods_info_vp)
    ViewPager goodsInfoViewPager;
    @BindView(R.id.goods_info_video_txt)
    TextView goodsInfoVideoTxt;
    @BindView(R.id.goods_info_img_txt)
    TextView goodsInfoImgTxt;
    @BindView(R.id.goods_info_like_img)
    ImageView goodsInfoLikeImg;
    @BindView(R.id.goods_info_like_txt)
    TextView goodsInfoLikeTxt;
    @BindView(R.id.goods_info_like)
    RelativeLayout goodsInfoLike;
    @BindView(R.id.goods_info_cart_img)
    ImageView goodsInfoCartImg;
    @BindView(R.id.goods_info_cart_txt)
    TextView goodsInfoCartTxt;
    @BindView(R.id.goods_info_cart_number)
    TextView goodsInfoCartNumber;
    @BindView(R.id.goods_info_buy_1)
    ConstraintLayout goodsInfoBuy1;
    @BindView(R.id.goods_info_add_cart)
    TextView goodsInfoAddCart;
    @BindView(R.id.goods_info_buy_2)
    RelativeLayout goodsInfoBuy2;
    @BindView(R.id.goods_info_buy)
    TextView goodsInfoBuy;
    @BindView(R.id.goods_info_buy_3)
    RelativeLayout goodsInfoBuy3;
    @BindView(R.id.webView_goods)
    WebView webViewGoods;
    @BindView(R.id.goods_selector)
    LinearLayout goodsSelector;
    @BindView(R.id.goods_img)
    ConstraintLayout goodsImg;
    @BindView(R.id.cl)
    ConstraintLayout cl;
    @BindView(R.id.goods_info_cart_img1)
    ImageView goodsInfoCartImg1;
    private String goodsId;
    private Context mContext;
    private GoodsInfoEntity.DataEntity dataEntity;
    private GoodsInfoDetailAdapter goodsInfoDetailAdapter;
    private GoodsImageFragment goodsImageFragment;
    private GoodsVideoFragment goodsVideoFragment;
    private GoodsInfoViewPagerAdapter goodsInfoViewPagerAdapter;
    private List<BaseFragment> baseFragmentList;
    private FragmentManager fragmentManager;
    private IWXAPI iwxapi;
    private String userId;
    private CartDialogWindow cartDialogWindow;
    private static final int SHOW_CART_WINDOW_TO_CART = 0;
    private static final int SHOW_CART_WINDOW_TO_SALE = 1;
    private CartUpdateBrocarstReciver cartUpdateBrocarstReciver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_info);
        ButterKnife.bind(this);
        ImmersionBar.with(this).statusBarColor("#4c333333").titleBar(goodsInfoTitle).init();
        mContext = this;
        iwxapi = WXAPIFactory.createWXAPI(this, MyApplication.getInstance().getWX_ID(), false);
        if (currentUser != null) {
            userId = currentUser.getId();
        } else {
            userId = "";
        }
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
        unregisterReceiver(cartUpdateBrocarstReciver);

    }

    private void initView() {
        cartUpdateBrocarstReciver = new CartUpdateBrocarstReciver().setCartUpdateListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastReciverAction.UPDATE_MY_CART);
        registerReceiver(cartUpdateBrocarstReciver, intentFilter);
        RxViewHelper.getInstance().clicks(goodsInfoVideoTxt, aVoid ->
        {
            goodsInfoVideoTxt.setEnabled(false);
            goodsInfoImgTxt.setEnabled(true);
            goodsInfoViewPager.setCurrentItem(0);
        });
        RxViewHelper.getInstance().clicks(goodsInfoImgTxt, aVoid ->
        {
            goodsInfoImgTxt.setEnabled(false);
            goodsInfoVideoTxt.setEnabled(true);
            goodsInfoViewPager.setCurrentItem(1);

        });
        RxViewHelper.getInstance().clicks(goodsInfoBack, aVoid ->
                finish()
        );
        RxViewHelper.getInstance().clicks(goodsInfoBuy1, aVoid ->
                {
                    if (currentUser == null) {
                        BaseTool.goActivity(mContext, LoginActivity.class, null);
                        return;
                    }
                    BaseTool.goActivity(mContext, CartActivity.class, null);
                }

        );
        RxViewHelper.getInstance().clicks(goodsInfoBuy2, aVoid ->
                {
                    if (currentUser == null) {
                        BaseTool.goActivity(mContext, LoginActivity.class, null);
                        return;
                    }
                    if (cartDialogWindow != null && !cartDialogWindow.isShowing()) {
                        cartDialogWindow.show(GoodsInfoActivity.SHOW_CART_WINDOW_TO_CART);
                    }
                }

        );
        RxViewHelper.getInstance().clicks(goodsInfoBuy3, aVoid ->
                {
                    if (currentUser == null) {
                        BaseTool.goActivity(mContext, LoginActivity.class, null);
                        return;
                    }
                    if (cartDialogWindow != null && !cartDialogWindow.isShowing()) {
                        cartDialogWindow.show(GoodsInfoActivity.SHOW_CART_WINDOW_TO_SALE);
                    }
                }
        );
        RxViewHelper.getInstance().clicks(goodsInfoLike, aVoid -> { //收藏代码
                    if (TextUtils.isEmpty(dataEntity.getIs_favorite())) {
                        if (currentUser == null) {
                            BaseTool.goActivity(mContext, LoginActivity.class, null);
                            return;
                        }
                        //进行收藏
                        NetClient.getInstance().getShopService(ShopMainIF.class)
                                .addLikeGoodsInfo(AppUtils.getSignParams(dataEntity.getCategory_id(), dataEntity.getId(), currentUser.getId()), dataEntity.getCategory_id(), dataEntity.getId(), currentUser.getId())
                                .compose(new BaseTransformer<>(this, true, false))
                                .subscribe(new BaseObserver<BaseResponse<AddGoodsLikeEntity.DataEntity>>() {
                                    @Override
                                    public void onSuccess(BaseResponse<AddGoodsLikeEntity.DataEntity> response) {
                                        dataEntity.setIs_favorite(response.getData().id);
                                        goodsInfoLikeImg.setImageResource(R.drawable.icon_my_like_2_0);
                                        goodsInfoLikeTxt.setText("已收藏");
                                    }
                                });
                    } else {
                        //取消收藏
                        if (currentUser == null) {
                            BaseTool.goActivity(mContext, LoginActivity.class, null);
                            return;
                        }
                        NetClient.getInstance().getShopService(ShopMainIF.class).deleteLikeGoodsInfo(AppUtils.getSignParams(dataEntity.getIs_favorite(), currentUser.getId()), dataEntity.getIs_favorite(), currentUser.getId())
                                .compose(new BaseTransformer<>(this, true, false)).subscribe(new BaseObserver<BaseResponse<AddGoodsLikeEntity.DataEntity>>() {
                            @Override
                            public void onSuccess(BaseResponse<AddGoodsLikeEntity.DataEntity> response) {
                                dataEntity.setIs_favorite("");
                                goodsInfoLikeImg.setImageResource(R.drawable.icon_like_false_2_0);
                                goodsInfoLikeTxt.setText("收藏");
                            }
                        });
                    }
                }

        );
        RxViewHelper.getInstance().clicks(goodsInfoShare, aVoid ->
                {
                    DialogShare dialogShare = new DialogShare(this);
                    dialogShare.show();
                    //分享到微信
                    dialogShare.getWeChatSubject().subscribe(o -> {
                        doShareWeChat("weChat");
                        dialogShare.cancel();
                    });
                    //分享到朋友圈
                    dialogShare.getFriendsSubject().subscribe(o -> {
                        doShareWeChat("friends");
                        dialogShare.cancel();
                    });
                }
        );
        Bundle bundle = getIntent().getExtras();
        goodsId = bundle.getString("goods_info_id", null);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        goodsInfoRl.setLayoutManager(linearLayoutManager);
        goodsInfoRl.setNestedScrollingEnabled(false);
        baseFragmentList = new ArrayList<>();
        fragmentManager = getSupportFragmentManager();
        goodsInfoViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    goodsInfoVideoTxt.setEnabled(false);
                    goodsInfoImgTxt.setEnabled(true);
                } else if (position == 1) {
                    goodsInfoImgTxt.setEnabled(false);
                    goodsInfoVideoTxt.setEnabled(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initData() {
        NetClient.getInstance()
                .getShopService(ShopMainIF.class)
                .getGoodsInfo(goodsId, userId)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<GoodsInfoEntity.DataEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<GoodsInfoEntity.DataEntity> response) {
                        Log.d("商品详情", "onSuccess: " + response.getData().getId());
                        dataEntity = response.getData();
                        if (!TextUtils.isEmpty(response.getData().getVideo())) {
                            goodsSelector.setVisibility(View.VISIBLE);
                            goodsVideoFragment = GoodsVideoFragment.newInstance(response.getData().getVideo());
                            baseFragmentList.add(goodsVideoFragment);
                        } else {
                            goodsSelector.setVisibility(View.GONE);
                        }
                        goodsImageFragment = GoodsImageFragment.newInstance(Config.URL_HOST_SHOP + response.getData().getImg(), "");
                        baseFragmentList.add(goodsImageFragment);
                        goodsInfoViewPagerAdapter = new GoodsInfoViewPagerAdapter(fragmentManager, baseFragmentList);
                        goodsInfoViewPager.setAdapter(goodsInfoViewPagerAdapter);
                        goodsInfoMoney.setText(response.getData().getSell_price());
                        goodsInfoGp.setText("GP：" + response.getData().getGp_price());
                        goodsInfoNjf.setText("牛积分：" + response.getData().getNiu_score());
                        goodsInfoTitleTxt.setText(response.getData().getName());
                        if (!TextUtils.isEmpty(dataEntity.getIs_favorite())) {
                            goodsInfoLikeImg.setImageResource(R.drawable.icon_my_like_2_0);
                            goodsInfoLikeTxt.setText("已收藏");
                        }
//                        goodsInfoDetailAdapter = new GoodsInfoDetailAdapter(getStringList(response.getData().getContent()), mContext);
//                        goodsInfoRl.setAdapter(goodsInfoDetailAdapter);
                        setWebviews(response.getData().getContent());
                        cartDialogWindow = new CartDialogWindow(mContext, response.getData());
                    }
                });
        getCart();
    }

    private void getCart() {
        //获取购物车列表
        if (currentUser != null) {
            NetClient.getInstance().getShopService(ShopMainIF.class).getCartListInfo(AppUtils.getSignParams(currentUser.getId()), currentUser.getId())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse<MyCartEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<MyCartEntity> response) {
                            try {
                                goodsInfoCartNumber.setText(response.getData().getCount());                                if (!TextUtils.isEmpty(response.getData().getCount())){
                                    if (Integer.parseInt(response.getData().getCount())>0){
                                        goodsInfoCartImg1.setVisibility(View.VISIBLE);
                                        goodsInfoCartImg.setVisibility(View.GONE);
                                    }else {
                                        goodsInfoCartImg1.setVisibility(View.GONE);
                                        goodsInfoCartImg.setVisibility(View.VISIBLE);
                                    }
                                }
                            }catch (Exception e){

                            }
                        }
                    });
        }
    }

    //分享到微信或者朋友圈
    private void doShareWeChat(String type) {
//        WXImageObject wxImageObject = new WXImageObject(mBitmap);
//        WXMediaMessage msg = new WXMediaMessage();
//        msg.mediaObject = wxImageObject;
//        //设置缩略图
//        Bitmap mBp = Bitmap.createScaledBitmap(mBitmap, 120, 120, true);
//        msg.thumbData = bmpToByteArray(mBp, true);
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = buildTransaction("img");//  transaction字段用
//        req.message = msg;
//        if (type.equals("weChat")) {
//            req.scene = SendMessageToWX.Req.WXSceneSession;
//        } else if (type.equals("friends")) {
//            req.scene = SendMessageToWX.Req.WXSceneTimeline;
//        }
//        iwxapi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    public void updateCart() {
        getCart();
    }

    public void setWebviews(String body) {
        body = body.replaceAll("/upload", Config.URL_HOST_SHOP + "upload");
        body = body.replaceAll("<img", "<img width=\"100%\" ");
        Log.d("body", "setWebviews: " + body);
        webViewGoods.getSettings().setJavaScriptEnabled(true);
        webViewGoods.setScrollBarStyle(webViewGoods.SCROLLBARS_OUTSIDE_OVERLAY);
        webViewGoods.setHorizontalScrollBarEnabled(false);
        webViewGoods.getSettings().setSupportZoom(true);
        webViewGoods.getSettings().setBuiltInZoomControls(true);
        webViewGoods.setInitialScale(70);
        webViewGoods.setHorizontalScrollbarOverlay(true);
        webViewGoods.loadDataWithBaseURL(null, body, "text/html", "utf-8", null);
        webViewGoods.getSettings().setJavaScriptEnabled(true);
        webViewGoods.setWebChromeClient(new WebChromeClient());
    }


}
